﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;
using Newtonsoft.Json;

namespace GWEB.WebFrame.Customer
{
    public class DistributionController : Controller
    {
        [ActionFilter(IsLogin = true)]
        public ActionResult Index(String Ids,String KeyCodes)
        {
            if (!Fun.IDVerify(Ids, KeyCodes))
                return Content(WebMessage.NoGrant);

            ResultData result = CheckCustomerDist(Ids);
            ViewBag.Error = result.message;
            ViewBag.Ids = Ids;
            ViewBag.KeyCodes = KeyCodes;
            ViewBag.TotalDis = Ids.Split(',').Length;//选择的待分配

            DataRow drUser = BasePage.GetUser(Session);
            String dataCond = GrantData.GetDataCond(BasePage.bd, "Customer", drUser, null);
            String sql = "select count(*) from cu_Customers where CustState in (1,2,3) " + dataCond;
            ViewBag.TotalRece = BasePage.bd.ExecuteScalarString(sql);//待领取
            return View(BasePage.V("Customer/Distribution"));            
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult UserAdviser()
        {
            //分配只能分配给本加盟商的顾问
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            String sql = @"select iuserid as id,sshowname,0 AgentCount from tb_sys_users where bstopflag=0 and UserType = 1 and leagueId="+ leagueId;
            Dictionary<String,Object>[] dt = BasePage.bd.ExecuteDictArray(sql);
            return BasePage.Json(ResultData.OK(dt));
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult Finish(String Ids, String KeyCodes,String adviserIds, String agentCounts)
        {
            if (!Fun.IDVerify(Ids, KeyCodes))
                return BasePage.Json(ResultData.Error(WebMessage.NoGrant));
            if (adviserIds.Equals("")|| agentCounts.Equals(""))
                return BasePage.Json(ResultData.Error("请选择顾问并填入相应分配数"));            

            ResultData result = CheckCustomerDist(Ids);
            if (!result.Check()) return BasePage.Json(result);

            String[] cid = Ids.Split(',');
            String[] adviserId = adviserIds.Split(',');
            String[] agentCount = agentCounts.Split(',');
            String[] sqls = new String[cid.Length*2];//插入一条分配记录，并修改客户表记录

            DataRow drUser = BasePage.GetUser(Session);
            String distId = drUser["iuserid"].ToString();
            String createDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            String receInterval= BasePage.getDict(Session).GetValue2("D02", "3");
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());

            int j = 0;//累计计分配数
            int k = -1;//顾问数
            int totalDis = cid.Length;

            
            //分配顾问：依据顾问的分配数量来分配客户，如3个客户，分2个顾问，分别为2，1个
            for (int i = 0; i < cid.Length; i++)
            {
                if (i >= j)
                {
                    k++;
                    if(k>=agentCount.Length)
                        return BasePage.Json(ResultData.Error("分配总数与待分配不一致"));
                    j += int.Parse(agentCount[k]);
                }

                Dictionary<String, Object> data = new Dictionary<String, Object>();
                data.Add("Cid", cid[i]);
                data.Add("DistId", distId);
                data.Add("CreateDate", createDate);
                data.Add("AdviserId", adviserId[k]);
                data.Add("State", 0);
                data.Add("ReceInterval", receInterval);
                data.Add("LeagueId", leagueId);
                sqls[i] = BaseData.MapToSql("cu_Cus_Distribution", "id", "-1", data);
                //修改客户表记录
                sqls[i+ totalDis] = String.Format(@"update cu_Customers set LateLyDistDate='{0}',LatelyDistId={1},LatelyReceId={2},CustState=1 where id={3} and CustState in (0,1,2,3,7)",
                    createDate, distId, adviserId[k], cid[i]);
            }
            for(k++;k<agentCount.Length;k++)
                j += int.Parse(agentCount[k]);
            if (j != totalDis) return BasePage.Json(ResultData.Error("分配总数与待分配不一致"));
            bool t = BasePage.bd.ExecuteSQL(sqls, sqls.Length);           
            return BasePage.Json(t ? ResultData.OK() : ResultData.Error("操作失败"));
        }
        ResultData CheckCustomerDist(String Ids) {
            //检查是否分配记录，检查总数是否对??
            String sql = String.Format("select count(*) from cu_Customers where id in ({0}) and CustState not in (0,1,2,3,7)", Ids);
            int noDist = BasePage.bd.ExecuteScalarInt(sql);
            if (noDist > 0) return ResultData.Error("请选择待分配、已分配、历史客户");
            return ResultData.OK();
        }

        //设为历史客户
        [ActionFilter(IsLogin = true)]
        public JsonResult History(String id, String keyCode)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Error(WebMessage.NoGrant));
            
            String sql = String.Format("update cu_Customers set custState=7 where custState=0 and id in ({0})", id);            
            bool t = BasePage.bd.ExecuteSQL(sql);
            return BasePage.Json(t ? ResultData.OK("设置历史客户成功") : ResultData.Error("设置历史客户失败"));
        }

    }
}